package com.ruoyi.system.recovery.service.impl;

import java.util.List;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.SysYesNo;
import com.ruoyi.common.enums.zyl.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.recovery.domain.RecoveryDetail;
import com.ruoyi.system.recovery.domain.RecoveryInfo;
import com.ruoyi.system.recovery.domain.RecoverySaleMoney;
import com.ruoyi.system.recovery.domain.RecoveryService;
import com.ruoyi.system.recovery.domain.bo.RecoveryAuditBo;
import com.ruoyi.system.recovery.domain.bo.RecoveryInfoBo;
import com.ruoyi.system.recovery.domain.bo.RecoveryServiceBo;
import com.ruoyi.system.recovery.domain.param.RecoveryInfoParam;
import com.ruoyi.system.recovery.domain.vo.RecoveryInfoVo;
import com.ruoyi.system.recovery.mapper.RecoveryInfoMapper;
import com.ruoyi.system.recovery.service.IRecoveryDetailService;
import com.ruoyi.system.recovery.service.IRecoveryInfoService;
import com.ruoyi.system.service.ISysConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 回收账号Service业务层处理
 *
 * @author ruoyi
 * @date 2025-06-04
 */
@Service
@RequiredArgsConstructor
public class RecoveryInfoServiceImpl extends ServiceImpl<RecoveryInfoMapper, RecoveryInfo> implements IRecoveryInfoService {

    private final IRecoveryDetailService recoveryDetailService;
    private final ISysConfigService sysConfigService;

    /**
     * 查询回收账号
     *
     * @param id 回收账号主键
     * @return 回收账号
     */
    @Override
    public RecoveryInfoVo selectRecoveryInfoById(Long id) {
        RecoveryInfo recoveryInfo = super.getById(id);
        RecoveryInfoVo vo = new RecoveryInfoVo();
        BeanUtils.copyProperties(recoveryInfo, vo);
        vo.setDetail(recoveryDetailService.getById(id));
        return vo;
    }

    /**
     * 查询回收账号列表
     *
     * @param recoveryInfo 回收账号
     * @return 回收账号
     */
    @Override
    public List<RecoveryInfoVo> selectRecoveryInfoList(RecoveryInfoParam recoveryInfo) {
        if(recoveryInfo.getSearchType() != null) {
            recoveryInfo.setSearchColumn(recoveryInfo.getSearchType().getColumn());
        }
        return baseMapper.selectRecoveryInfoList(recoveryInfo);
    }

    /**
     * 新增回收账号
     *
     * @param recoveryInfo 回收账号
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @Log(title = "创建回收数据", businessType = BusinessType.INSERT, businessId = "#recoveryInfo.id")
    public boolean insertRecoveryInfo(RecoveryInfo recoveryInfo) {
        recoveryInfo.setInventoryStatus(InventoryStatusEnum.PENDING_PROCESSING);
        recoveryInfo.setRebindingTime(DateUtils.getNowDate());
        recoveryInfo.setRebindingType(SysRebindingTypeEnum.IS_REBINDING);
        recoveryInfo.setIsAutomatic(IsAutomaticEnum.UNAUTHORIZED);
        recoveryInfo.setFinds(SysRecoveryFindsEnum.NORMAL);
        recoveryInfo.setFreeze(SysRecoveryFreezeEnum.WAITING_INSPECT);
        recoveryInfo.setSaleStatus(SysYesNo.NO);
        recoveryInfo.setAftermarket(SysYesNo.NO);
        if (recoveryInfo.getIsFriend() == null) {
            recoveryInfo.setIsFriend(SysYesNo.NO);
        }
        if (recoveryInfo.getContract() == null) {
            recoveryInfo.setContract(SysContractStatusEnum.UNSIGNED);
        }

        boolean success = super.save(recoveryInfo);
        if (success) {
            RecoveryDetail recoveryDetail = new RecoveryDetail();
            recoveryDetail.setRecoveryInfoId(recoveryInfo.getId());
            recoveryDetail.insert();

            if (recoveryInfo.getSaleMoney() != null) {
                RecoverySaleMoney recoverySaleMoney = new RecoverySaleMoney();
                recoverySaleMoney.setRecoveryInfoId(recoveryInfo.getId());
                recoverySaleMoney.setSaleMoney(recoveryInfo.getSaleMoney());
                recoverySaleMoney.insert();
            }
        }


        return success;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean editRecoveryInfo(RecoveryInfo recoveryInfo) {
        boolean success = super.updateById(recoveryInfo);
        if (success && recoveryInfo.getSaleMoney() != null) {
            RecoverySaleMoney recoverySaleMoney = new RecoverySaleMoney();
            recoverySaleMoney.setRecoveryInfoId(recoveryInfo.getId());
            recoverySaleMoney.setSaleMoney(recoveryInfo.getSaleMoney());
            recoverySaleMoney.insert();
        }
        return success;
    }

    /**
     * 编辑账号详情
     *
     * @param recoveryInfo 回收账号
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean editRecoveryGameInfo(RecoveryInfoBo recoveryInfo) {
        String isProcess = sysConfigService.selectConfigByKey("is-process");
        if("1".equals(isProcess)) {
            // 需要审核
            recoveryInfo.setInventoryStatus(InventoryStatusEnum.PENDING_APPROVAL);
        } else {
            // 不需要审核
            recoveryInfo.setInventoryStatus(InventoryStatusEnum.ALREADY_LISTED);
            recoveryInfo.setRecoveryStatus(InventoryOrderStatusEnum.COMPLETE);
        }
        boolean success = super.updateById(recoveryInfo);
        if (success) {
            if (recoveryInfo.getDetail().getRecoveryInfoId() == null) {
                recoveryInfo.getDetail().setRecoveryInfoId(recoveryInfo.getId());
            }
            recoveryInfo.getDetail().updateById();

            if (recoveryInfo.getSaleMoney() != null) {
                RecoverySaleMoney recoverySaleMoney = new RecoverySaleMoney();
                recoverySaleMoney.setRecoveryInfoId(recoveryInfo.getId());
                recoverySaleMoney.setSaleMoney(recoveryInfo.getSaleMoney());
                recoverySaleMoney.insert();
            }
        }
        return success;
    }

    /**
     * 批量删除回收账号
     *
     * @param id 需要删除的回收账号主键
     * @return 结果
     */
    @Override
    public boolean deleteRecoveryInfoById(Long id) {
        return super.removeById(id);
    }

    @Override
    @Log(title = "添加备注", businessType = BusinessType.UPDATE, businessId = "#id", remark = "#remark")
    public boolean updateRemark(Long id, String remark) {
        return super.update(Wrappers.lambdaUpdate(RecoveryInfo.class).eq(RecoveryInfo::getId, id).set(RecoveryInfo::getRemark, remark));
    }

    @Override
    @Log(title = "库存审核通过", businessType = BusinessType.UPDATE, businessId = "#recoveryAuditBo.recoveryInfoId", remark = "库存审核通过")
    public boolean recoveryApproved(RecoveryAuditBo recoveryAuditBo) {
        return super.update(Wrappers.lambdaUpdate(RecoveryInfo.class)
                .eq(RecoveryInfo::getId, recoveryAuditBo.getRecoveryInfoId())
                .set(RecoveryInfo::getInventoryStatus, InventoryStatusEnum.ALREADY_LISTED)
                .set(RecoveryInfo::getRecoveryStatus, InventoryOrderStatusEnum.COMPLETE)
        );
    }

    @Override
    @Log(title = "库存审核驳回", businessType = BusinessType.UPDATE, businessId = "#recoveryAuditBo.recoveryInfoId", remark = "#recoveryAuditBo.remark")
    public boolean recoveryOverrule(RecoveryAuditBo recoveryAuditBo) {
        return super.update(Wrappers.lambdaUpdate(RecoveryInfo.class)
                .eq(RecoveryInfo::getId, recoveryAuditBo.getRecoveryInfoId())
                .set(RecoveryInfo::getInventoryStatus, InventoryStatusEnum.PENDING_APPROVAL)
        );
    }

    @Override
    @Log(title = "提交暂卖", businessType = BusinessType.UPDATE, businessId = "#recoveryAuditBo.recoveryInfoId", remark = "提交暂卖")
    public boolean temporarilySold(RecoveryAuditBo recoveryAuditBo) {
        return super.update(Wrappers.lambdaUpdate(RecoveryInfo.class)
                .eq(RecoveryInfo::getId, recoveryAuditBo.getRecoveryInfoId())
                .set(RecoveryInfo::getInventoryStatus, InventoryStatusEnum.TEMPORARILY_SOLD)
        );
    }

    @Override
    @Log(title = "取消暂卖", businessType = BusinessType.UPDATE, businessId = "#recoveryAuditBo.recoveryInfoId", remark = "#recoveryAuditBo.remark")
    public boolean temporarilySoldCancel(RecoveryAuditBo recoveryAuditBo) {
        return super.update(Wrappers.lambdaUpdate(RecoveryInfo.class)
                .eq(RecoveryInfo::getId, recoveryAuditBo.getRecoveryInfoId())
                .set(RecoveryInfo::getInventoryStatus, InventoryStatusEnum.ALREADY_LISTED)
        );
    }

    @Override
    public AjaxResult editIsProcess(String value) {
        if("0".equals(value)){
            // 关闭时校验是否存在未审核的数据
            Long count = super.count(Wrappers.lambdaQuery(RecoveryInfo.class).eq(RecoveryInfo::getInventoryStatus, InventoryStatusEnum.PENDING_APPROVAL));
            if(count.intValue() > 0) {
                return AjaxResult.error("请先处理待审核库存！");
            }
        }
        boolean success = sysConfigService.updateConfigByKey("is-process",  value);
        return success ? AjaxResult.success() : AjaxResult.error();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addServices(RecoveryServiceBo recoveryServiceBo) {
        RecoveryInfo recoveryInfo = super.getById(recoveryServiceBo.getRecoveryInfoId());
        if(recoveryInfo == null) {
            return AjaxResult.error("未找到账号信息");
        }
        recoveryInfo.setInventoryStatus(InventoryStatusEnum.AFTER_SALE_SERVICE);
        recoveryInfo.setRecoveryStatus(InventoryOrderStatusEnum.AFTER_SALE_SERVICE);
        recoveryInfo.updateById();

        // 添加售后
        RecoveryService recoveryService = new RecoveryService();
        recoveryService.setRecoveryInfoId(recoveryServiceBo.getRecoveryInfoId());
        recoveryService.setChannelType(ServiceChannelTypeEnum.AUTOMATIC);
        recoveryService.setServicesReason(recoveryServiceBo.getServicesReason());
        recoveryService.setSettleStatus("0");
        recoveryService.setStatus(ServiceStatusEnum.UNTREATED);
        recoveryService.setRemark(recoveryServiceBo.getRemark());
        recoveryService.setBindingImg(recoveryServiceBo.getBindingImg());
        recoveryService.setEvidenceImg(recoveryServiceBo.getEvidenceImg());
        recoveryService.setEvidenceVideo(recoveryServiceBo.getEvidenceVideo());
        recoveryService.setOtherImg(recoveryServiceBo.getOtherImg());
        return recoveryService.insert() ? AjaxResult.success() : AjaxResult.error();
    }

    @Override
    public AjaxResult cancleRecovery(Long id) {
        RecoveryInfo recoveryInfo = super.getById(id);
        if(recoveryInfo == null) {
            return AjaxResult.error("未找到账号信息");
        }
        boolean success = super.update(Wrappers.lambdaUpdate(RecoveryInfo.class)
                .eq(RecoveryInfo::getId, id)
                .set(RecoveryInfo::getInventoryStatus, InventoryStatusEnum.INVALID_ACCOUNT)
                .set(RecoveryInfo::getRecoveryStatus, InventoryOrderStatusEnum.INVALID_ACCOUNT)
        );
        return success ? AjaxResult.success() : AjaxResult.error();
    }

}
